# coding:utf8

from appserver import db_store
from sqlalchemy.orm import relationship, backref

from models.entity.user import User
from models.entity.role_with_user import RoleWithUser
from models.entity.role import Role
from models.entity.role_with_button import RoleWithButton
from models.entity.tree_model_base import TreeModelBase

from sqlalchemy import or_
from sqlalchemy import and_

"""
按钮表
"""


class Button(TreeModelBase):
    __tablename__ = "buttons"
    __bind_key__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'按钮编号')
    name = db_store.Column(db_store.String(64), nullable=False, comment=u'按钮名称')
    code = db_store.Column(db_store.String(32), nullable=False, unique=True, comment=u"按钮编码")
    module_id = db_store.Column(db_store.Integer, db_store.ForeignKey('modules.id'), comment=u"模块ID")
    parent_id = db_store.Column(db_store.Integer, nullable=False, comment=u"父ID")
    path = db_store.Column(db_store.String(255), comment=u"路径")
    depth = db_store.Column(db_store.Integer, comment=u"深度")
    child_num = db_store.Column(db_store.Integer, comment=u"子类数量", default=0)
    dis_order = db_store.Column(db_store.Integer, comment=u"排序")
    target = db_store.Column(db_store.String(20), comment=u"目标")  # 1-当前页面打开 2-新标签打开 3-本页面模态框
    url = db_store.Column(db_store.String(255), default="", comment=u"地址")
    icon = db_store.Column(db_store.String(32), comment=u"图标")
    status = db_store.Column(db_store.Integer, comment=u"状态")  # 0-正常 1-禁用
    Module = relationship("Module", backref=backref('modules', order_by=id))

    def __repr__(self):
        return "<Button %s>" % (self.name)


    @staticmethod
    def get_button_by_id(button_id):
        return Button.query.filter_by(id=button_id).first()

    @staticmethod
    def get_button_by_code(code):
        return Button.query.filter_by(code=code).first()

    @staticmethod
    def get_buttons_by_user(the_user):
        # 通过用户实例获取其按钮列表,  本来button和user没有关系,但是通过两张中间表进行关联RoleWithUser,RoleWithButton
        if not isinstance(the_user, User):
            print("get_buttons_by_user error: the_user must be an User")
            return -1
        role_list = []
        role_connectors = RoleWithUser.query.filter_by(user_id=the_user.id).all()
        for role_connector in role_connectors:
            the_role = Role.query.filter_by(id=role_connector.role_id).first()
            if not the_role:
                print("get_buttons_by_user error: role(id=%d) is not exist" % role_connector.role_id)
                return -2
            role_list.append(the_role)
        button_set = set()
        for item in role_list:
            item_button_list = RoleWithButton.query.filter_by(role_id=item.id).all()
            for button in item_button_list:
                button_set.add(Button().get_entity_by_id(button.button_id))
        return list(button_set)

    @staticmethod
    def get_button_tree_by_module(the_module):
        # 通过模块实例获取其按钮树
        buttons = Button.query.filter_by(module_id=the_module.id).filter_by(parent_id=0).all()
        rlist = []
        for item in buttons:
            tdic = item.to_dict()
            tdic["children"]=item.get_tree_by_pid(item.id)
            rlist.append(tdic)
        return rlist

    @staticmethod
    def get_buttons_by_module_id(module_id):
        return Button.query.filter_by(module_id=module_id).all()

    #####我加的方法8-28
    @staticmethod
    def get_role_with_buttons_by_role_id(id_num):
        connectors = RoleWithButton.query.filter_by(role_id=id_num).all()
        # print('connectors', connectors)
        rlist = []
        for item in connectors:
            # print('item', item)
            rlist.append(Button.query.filter_by(id=item.button_id).first())
        print('rlist', rlist)
        return rlist

    @staticmethod
    def search(query_word):
        tmp = {}
        data = []
        buttons = Button.query.filter(
            or_(Button.code.like('%' + query_word + '%'), Button.name.like('%' + query_word + '%'))).all()
        for obj in buttons:
            print('obj', obj)
            print('obj类型',type(obj))
            # data.append(Button.get_button_dic(obj))   # 没有这个方法
            data.append(Button.to_dict(obj))
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return tmp
